package com.jtny.nytb.config.unifiedIdentification.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.jtny.component.core.util.PageUtils;
import com.jtny.component.core.util.QueryWrapperUtils;
import com.jtny.component.entity.PageData;
import com.jtny.component.enums.GenericStatusEnum;
import com.jtny.component.exception.ServiceException;
import com.jtny.component.util.Assert;
import com.jtny.component.util.BeanUtils;
import com.jtny.nytb.config.unifiedIdentification.dao.DataUnifiedIdentifierDAO;
import com.jtny.nytb.config.unifiedIdentification.domain.DataUnifiedIdentifierDO;
import com.jtny.nytb.config.unifiedIdentification.dto.UnifiedIdentifierQueryParamDTO;
import com.jtny.nytb.config.unifiedIdentification.dto.UnifiedIdentifierRequestDTO;
import com.jtny.nytb.config.unifiedIdentification.dto.UnifiedIdentifierResponseDTO;
import com.jtny.nytb.config.unifiedIdentification.service.UnifiedIdentifier;
import com.jtny.nytb.config.unifiedIdentification.vo.ExcelUnifiedIdentifierVO;
import com.jtny.nytb.config.unifiedIdentification.vo.UnifiedIdentifierQueryParamVO;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;


/**
 * @author 智慧能源中心 - 伍天宇
 * @package com.jtny.nytb.config.generic.identifier.biz.impl
 * @fileName UnifiedIdentifierBizImpl.java
 * @createTime 2023年09月26日 23:14
 * @Copyright© 2023 jtny
 * 江投能源技术研究院 版权所有
 */
@Service
@AllArgsConstructor
public class UnifiedIdentifierImpl implements UnifiedIdentifier {

    @Autowired
    private DataUnifiedIdentifierDAO dataUnifiedIdentifierDAO;

//    private UnifiedIdentifierClient unifiedIdentifierClient;

    /**
     * 详情
     *
     * @param id id
     * @return {@link UnifiedIdentifierResponseDTO}
     */
    @Override
    public UnifiedIdentifierResponseDTO detail(Long id) throws ServiceException {
        DataUnifiedIdentifierDO dataUnifiedIdentifierDO = dataUnifiedIdentifierDAO.selectById(id);
        Assert.notNull(dataUnifiedIdentifierDO, "统一标识符不存在");
        return BeanUtils.copyToObject(dataUnifiedIdentifierDO, UnifiedIdentifierResponseDTO.class);
    }

    /**
     * 分页
     *
     * @param unifiedIdentifierQueryParamVO 查询参数
     * @return {@link PageData}<{@link UnifiedIdentifierResponseDTO}>
     */
    @Override
    public PageData<UnifiedIdentifierResponseDTO> page(UnifiedIdentifierQueryParamVO unifiedIdentifierQueryParamVO) throws ServiceException {
        UnifiedIdentifierQueryParamDTO unifiedIdentifierQueryParamDTO = BeanUtils.copyToObject(unifiedIdentifierQueryParamVO, UnifiedIdentifierQueryParamDTO.class);
        QueryWrapper<DataUnifiedIdentifierDO> queryWrapper = QueryWrapperUtils.getQueryWrapper(unifiedIdentifierQueryParamDTO);
        queryWrapper.ne("status", 9);
        queryWrapper.orderByDesc("id");

        // 分页查询统一用户信息信息
        Page<DataUnifiedIdentifierDO> page = Page
                .of(unifiedIdentifierQueryParamDTO.getPageNo(), unifiedIdentifierQueryParamDTO.getPageSize());
        PageData<DataUnifiedIdentifierDO> pageDataForDO = PageUtils
                .getPageData(dataUnifiedIdentifierDAO.selectPage(page, queryWrapper), unifiedIdentifierQueryParamDTO);

        return pageDataForDO.transformData(UnifiedIdentifierResponseDTO.class);
    }

    /**
     * 更新
     *
     * @param unifiedIdentifier 统一标识符响应 DTO
     */
    @Override
    public void update(UnifiedIdentifierRequestDTO unifiedIdentifier) throws ServiceException {
        Integer status = unifiedIdentifier.getStatus();
        if (GenericStatusEnum.DELETED.getValue().equals(status)) {
            delete(unifiedIdentifier.getId());
        } else {
            updateUnifiedIdentifier(unifiedIdentifier);
        }
    }

    private void delete(Long id) throws ServiceException {
        DataUnifiedIdentifierDO dataUnifiedIdentifierDO = dataUnifiedIdentifierDAO.selectById(id);
        Assert.notNull(dataUnifiedIdentifierDO, "统一标识符不存在");
        dataUnifiedIdentifierDO.setStatus(GenericStatusEnum.DELETED.getValue());
        dataUnifiedIdentifierDAO.updateById(dataUnifiedIdentifierDO);
    }

    public void updateUnifiedIdentifier(UnifiedIdentifierRequestDTO unifiedIdentifier) {
        DataUnifiedIdentifierDO toUpdate = BeanUtils.copyToObject(unifiedIdentifier, DataUnifiedIdentifierDO.class);
        Assert.isTrue(checkUnifiedIdentifier(unifiedIdentifier.getUnifiedIdentifier(), unifiedIdentifier.getId()), "统一标识符已存在");
        Assert.isTrue(checkUnifiedIdentifierName(unifiedIdentifier.getUnifiedIdentifierName(), unifiedIdentifier.getId()),"统一标识名称已存在");
        SqlHelper.retBool(dataUnifiedIdentifierDAO.updateById(toUpdate));
    }


    /**
     * 导入统一标识符 Excel
     *
     * @param unifiedIdentifierList 统一标识符列表
     * @return {@link Boolean}
     */
    @Override
    public Boolean importUnifiedIdentifierExcel(List<ExcelUnifiedIdentifierVO> unifiedIdentifierList) {

        List<ExcelUnifiedIdentifierVO> cleanUnifiedIdentifierList = cleanUnifiedIdentifierByName(unifiedIdentifierList);
        List<UnifiedIdentifierRequestDTO> unifiedIdentifierDTOList = cleanUnifiedIdentifierList.stream()
                .map(ExcelUnifiedIdentifierVO::toBuildDto).collect(Collectors.toList());
        return saveBatchUnifiedIdentifierExcel(unifiedIdentifierDTOList);
    }


    /**
     * 批量保存统一标识
     *
     * @param unifiedIdentifierRequestDTOS 配置全局管理列表
     * @return {@link Boolean}
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveBatchUnifiedIdentifierExcel(List<UnifiedIdentifierRequestDTO> unifiedIdentifierRequestDTOS) {
        unifiedIdentifierRequestDTOS.forEach(this::save);
        return Boolean.TRUE;
    }

    /**
     * 保存 统一标识符
     *
     * @param unifiedIdentifier {@link UnifiedIdentifierRequestDTO} 统一标识符
     * @return {@link Boolean}
     */
    @Override
    public Boolean save(UnifiedIdentifierRequestDTO unifiedIdentifier) throws ServiceException {
        Long nameCount = dataUnifiedIdentifierDAO.selectCount(Wrappers.<DataUnifiedIdentifierDO>lambdaQuery(DataUnifiedIdentifierDO.class)
                .eq(DataUnifiedIdentifierDO::getUnifiedIdentifierName, unifiedIdentifier.getUnifiedIdentifierName())
                .ne(DataUnifiedIdentifierDO::getStatus,GenericStatusEnum.DELETED.getValue()));
        Assert.isTrue(nameCount == 0,"统一标识符名称重复");
        DataUnifiedIdentifierDO toSave = BeanUtils.copyToObject(unifiedIdentifier, DataUnifiedIdentifierDO.class);
        Assert.isNull(toSave.getId(), "统一标识符非法");
        Assert.isTrue(checkUnifiedIdentifier(unifiedIdentifier.getUnifiedIdentifier(), null), "统一标识符已存在");
//        save2Label(toSave);
        return SqlHelper.retBool(dataUnifiedIdentifierDAO.insert(toSave));
    }

    /**
     * 按名称清理统一标识符
     *
     * @param unifiedIdentifierList 统一标识符列表
     * @return {@link List}<{@link ExcelUnifiedIdentifierVO}>
     */
    private List<ExcelUnifiedIdentifierVO> cleanUnifiedIdentifierByName(List<ExcelUnifiedIdentifierVO> unifiedIdentifierList) {
        List<String> nameList = unifiedIdentifierList.stream()
                .map(ExcelUnifiedIdentifierVO::getUnifiedIdentifierName)
                .collect(Collectors.toList());
        List<String> existNameList = existUnifiedIdentifierByName(nameList);
        return unifiedIdentifierList.stream()
                .filter(excelAlgorithmVO ->!existNameList.contains(excelAlgorithmVO.getUnifiedIdentifierName()))
                .collect(Collectors.toList());
    }

    /**
     * 按名称存在统一标识符
     *
     * @param nameList 名称列表
     * @return {@link List}<{@link String}>
     */
    private List<String> existUnifiedIdentifierByName(List<String> nameList) {
        if(CollUtil.isNotEmpty(nameList)){
            LambdaQueryWrapper<DataUnifiedIdentifierDO> wrapper = Wrappers.<DataUnifiedIdentifierDO>lambdaQuery()
                    .in(DataUnifiedIdentifierDO::getUnifiedIdentifierName, nameList)
                    .ne(DataUnifiedIdentifierDO::getStatus, GenericStatusEnum.DELETED.getValue());
            List<DataUnifiedIdentifierDO> dictionaryList = dataUnifiedIdentifierDAO.selectList(wrapper);
            return dictionaryList.stream().map(DataUnifiedIdentifierDO::getUnifiedIdentifierName).collect(Collectors.toList());
        }
        return CollUtil.newArrayList();
    }

    /**
     * 校验名称是否重复
     *
     * @param unifiedIdentifier 名称
     * @param id   主键ID
     * @return {@link Boolean}
     */
    private Boolean checkUnifiedIdentifier(String unifiedIdentifier, Long id) {
        LambdaQueryWrapper<DataUnifiedIdentifierDO> wrapper = Wrappers.<DataUnifiedIdentifierDO>lambdaQuery()
                .eq(DataUnifiedIdentifierDO::getUnifiedIdentifier, unifiedIdentifier)
                .ne(DataUnifiedIdentifierDO::getStatus, GenericStatusEnum.DELETED.getValue());
        Optional.ofNullable(id).ifPresent(item -> wrapper.ne(DataUnifiedIdentifierDO::getId, item));
        return !dataUnifiedIdentifierDAO.exists(wrapper);
    }


    /**
     * 校验名称是否重复
     *
     * @param unifiedIdentifierName 名称
     * @param id   主键ID
     * @return {@link Boolean}
     */
    private Boolean checkUnifiedIdentifierName(String unifiedIdentifierName, Long id) {
        LambdaQueryWrapper<DataUnifiedIdentifierDO> wrapper = Wrappers.<DataUnifiedIdentifierDO>lambdaQuery()
                .eq(DataUnifiedIdentifierDO::getUnifiedIdentifierName, unifiedIdentifierName)
                .ne(DataUnifiedIdentifierDO::getStatus, GenericStatusEnum.DELETED.getValue());
        Optional.ofNullable(id).ifPresent(item -> wrapper.ne(DataUnifiedIdentifierDO::getId, item));
        return !dataUnifiedIdentifierDAO.exists(wrapper);
    }

    /**
     * save2 标签
     *
     * @param unifiedIdentifier 统一标识符
     */
//    private void save2Label(DataUnifiedIdentifierDO unifiedIdentifier) {
//        String type = unifiedIdentifier.getType();
//        DataLabelItemDO parentLabel = dataLabelItemDAO.selectOne(Wrappers.<DataLabelItemDO>lambdaQuery()
//                .eq(DataLabelItemDO::getLabelItemName, type).last("limit 1"));
//        Assert.notNull(parentLabel, "统一标识符标签类型不存在");
//        String unifiedIdentifierName = unifiedIdentifier.getUnifiedIdentifierName();
//        String path = type + ">" + unifiedIdentifierName;
//        saveLabelItem(unifiedIdentifierName, unifiedIdentifierName, path, parentLabel, parentLabel);
//    }

}
